﻿
using System;
using System.IO;
using System.Windows.Forms;
using BrightIdeasSoftware;
using GDFlacTool.Common;

namespace GDFlacTool.Forms
{
    public partial class FormEditFileName : Form
    {
        private readonly ObjectListView _objectListView;
        private Track _currentTrack;
        private int _index;

        public static Control TheActiveControl;
        public static Control ThePreviousControl;

        private event EventHandler EnterEventHandler = delegate { };

        private string _newFilePath = string.Empty;
        private string _oldFilePath = string.Empty;

        public FormEditFileName(ObjectListView listView)
        {
            InitializeComponent();
            
            _objectListView = listView;
        }

        private void Control_Enter(object sender, EventArgs e)
        {
            ThePreviousControl = TheActiveControl;
            TheActiveControl = sender as Control;
        }

        private void FormEditFileName_Load(object sender, EventArgs e)
        {
            EnterEventHandler += (Control_Enter);

            Controls.SetEnterEvent(EnterEventHandler);

            if(_objectListView.SelectedIndex >= 0)
            {
                _index = _objectListView.SelectedIndex;
            }
            else
            {
                _index = 0;
                _objectListView.SelectedIndex = 0;
            }

            _currentTrack = (Track)_objectListView.SelectedObject;

            UpdateText();
        }

        private void UpdateText()
        {
            _oldFilePath = _currentTrack.FullPath;
            txtCurrentName.Text = Path.GetFileNameWithoutExtension(_currentTrack.FullPath);
            lblCurrentFilePrefix.Text = Path.GetExtension(_currentTrack.FullPath);

            txtNewName.Text = txtCurrentName.Text;
            lblNewFilePrefix.Text = lblCurrentFilePrefix.Text;

            if (string.IsNullOrEmpty(txtNewName.Text))
            {
                Text = string.Format("Edit File Name (new length {0})", "0");
            }
            else
            {
                Text = string.Format("Edit File Name (new length {0})", txtNewName.Text.Length);
            }
        }

        private void txtNewName_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtNewName.Text))
            {
                Text = string.Format("Edit File Name (new length {0})", "0");
                _newFilePath = string.Empty;
            }
            else
            {
                Text = string.Format("Edit File Name (new length {0})", txtNewName.Text.Length);

                if(Functions.CheckFileNameForIllegalChars(txtNewName.Text))
                {
                    btnOk.Enabled = false;
                    btnEditNext.Enabled = false;
                    btnEditPrev.Enabled = false;
                    lblError.Visible = true;
                }
                else
                {
                    btnOk.Enabled = true;
                    btnEditNext.Enabled = true;
                    btnEditPrev.Enabled = true;
                    lblError.Visible = false;

                    if(!string.IsNullOrEmpty(txtNewName.Text))
                    {
                        _newFilePath = Path.Combine(_currentTrack.FilePath, string.Format("{0}{1}", txtNewName.Text, lblCurrentFilePrefix.Text));
                    }
                    else
                    {
                        _newFilePath = string.Empty;
                    }   
                }
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if(!RenameFile(_oldFilePath, _newFilePath))
            {
                DialogResult = DialogResult.Cancel;
            }
        }

        private void btnEditNext_Click(object sender, EventArgs e)
        {
            RenameFile(_oldFilePath, _newFilePath);

            _objectListView.RefreshObject(_currentTrack);

            if (_index + 1 < _objectListView.Items.Count)
            {
                _objectListView.SelectedIndex = ++_index;

                _currentTrack = (Track)_objectListView.SelectedObject;

                UpdateText();

                ThePreviousControl.Focus();
            }
            else
            {
                DialogResult = DialogResult.OK;
                Close();
            }
        }

        private void btnEditPrev_Click(object sender, EventArgs e)
        {
            RenameFile(_oldFilePath, _newFilePath);

            _objectListView.RefreshObject(_currentTrack);

            if (_index - 1 >= 0)
            {
                _objectListView.SelectedIndex = --_index;

                _currentTrack = (Track)_objectListView.SelectedObject;

                UpdateText();

                ThePreviousControl.Focus();

                ThePreviousControl.Focus();
            }
            else
            {
                DialogResult = DialogResult.OK;
                Close();
            }
        }

        private bool RenameFile(string oldFilePath, string newFilePath)
        {
            if (string.IsNullOrEmpty(newFilePath))
            {
                return false;
            }

            if(oldFilePath == newFilePath)
            {
                return false;
            }

            try
            {
                File.Move(oldFilePath, newFilePath);

                _currentTrack.FileName = Path.GetFileName(newFilePath);
                _currentTrack.FilePath = string.Format("{0}{1}", Path.GetDirectoryName(newFilePath), Path.DirectorySeparatorChar);
                _currentTrack.FullPath = newFilePath;

                _currentTrack.UpdateAfterRename();

                return true;
            }
            catch (IOException ex)
            {

                string message = string.Format("There was a problem renaming:\n\n{0}\n\nto\n\n{1}\n\n{2}",
                                                       oldFilePath, newFilePath, ex.Message);

                MessageBox.Show(this, message, "Varning", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                return false;
            }
        }
    }
}
